// components/Ranking.jsx
import React, { useState, useEffect } from 'react';
import styles from '../css/ranking.module.css';
import hourse2 from '../assets/hourse.png';
import flower from '../assets/flower.png';
import aircraftImg from '../assets/yan.png';
import tree from '../assets/tree2.png';
import meImg from '../assets/tree.png';
import blockImg from '../assets/top.png';
import starttwoImg from '../assets/starts.png';
import startoneImg from '../assets/starts.png';
import starthreeImg from '../assets/starts.png';
import send from '../assets/send.png';
import mines from '../assets/mine.png';
import { useNavigate } from 'react-router-dom';
import { fetchScenicData } from '../api/scenicData'; // 引入封装好的接口
import { imgUrl } from '../config'; // 导入imgUrl
const Ranking = () => {
    // 景区排行榜数据
    const [data, setData] = useState([]);
    const navigate = useNavigate();

    // 处理飞行器动画并导航到发布页面
    const aircraft = () => {
        const aircraftElement = document.querySelector(`.${styles.aircraft} img`);
        if (aircraftElement) {
            // 设置动画效果
            aircraftElement.style.marginTop = "-2000px";
            aircraftElement.style.transition = "all 2s";
            // 动画结束后导航到发布页面
            setTimeout(() => {
                navigate("/issue");
            }, 2000);
        }
    };

    // 组件挂载时加载景区排行榜数据
useEffect(() => {
  const fetchData = async () => {
    try {
      const response = await fetchScenicData();
      console.log('完整响应:', response); // 查看完整响应结构
      console.log('响应数据:', response.data); // 查看数据结构
      
      // 根据实际响应结构调整
      const data = response.data.data || response.data || [];
      console.log('最终数据:', data);
      
      setData(data);
    } catch (error) {
      console.error('获取景区数据时出错:', error);
      // 可以添加错误提示UI
      setData([]); // 确保设置为空数组
    }
  };

  fetchData();
}, []);

    // 点击景区项，保存数据到sessionStorage并导航到详情页
    const imgclick = (item) => {
        sessionStorage.setItem("jingid", item.id);
        sessionStorage.setItem("jingdata", JSON.stringify(item));
        navigate("/scenicdetails");
    };

    // 根据评分渲染星星图标
    // 参数score应为1-5之间的数字，支持0.5间隔
    const renderStars = (score) => {
        // 确保score在有效范围内
        if (score < 1) score = 1;
        if (score > 5) score = 5;
        
        // 计算完整星、半星和空星的数量
        const fullStars = Math.floor(score);
        const hasHalfStar = score % 1 >= 0.5;
        const emptyStars = 5 - fullStars - (hasHalfStar ? 1 : 0);
        
        // 生成星星图标数组
        const stars = [];
        // 添加完整星
        for (let i = 0; i < fullStars; i++) {
            stars.push(<img key={i} src={starttwoImg} alt="" />);
        }
        // 添加半星
        if (hasHalfStar) {
            stars.push(<img key={fullStars} src={starthreeImg} alt="" />);
        }
        // 添加空星
        for (let i = 0; i < emptyStars; i++) {
            stars.push(<img key={fullStars + (hasHalfStar ? 1 : 0) + i} src={startoneImg} alt="" />);
        }
        
        return <div className={styles.start}>{stars}</div>;
    };

    return (
        <div style={{ backgroundColor: '#f4f4f4', height: '100vh' }}>
            {/* 背景装饰 */}
            <div className={styles.back}></div>

            {/* 景区列表 */}
            <div className={styles['shop-item']}>
                {data.map((item, i) => (
                    <div key={item.id || i} className={styles.item} onClick={() => imgclick(item)}>
                        <div className={styles.image}>
                            {/* 排名标识 */}
                            <div>
                                <img className={styles.block} src={blockImg} alt="" />
                                <span style={{
                                    position: 'absolute',
                                    zIndex: 200,
                                    margin: '15px 13px',
                                    fontSize: '13px',
                                    color: '#ffffff'
                                }}>
                                    {i + 1}
                                </span>
                            </div>
                            {/* 景区图片 */}
                            <img className={styles.blocks} src={`${imgUrl}${item.img}`} alt={item.name} />
                        </div>

                        {/* 景区信息 */}
                        <div style={{
                            width: '55%',
                            marginLeft: '5px',
                            display: 'flex',
                            flexDirection: 'column',
                            justifyContent: 'space-around'
                        }}>
                            <b>{item.name}</b>
                            {renderStars(item.score)}
                            <span>{item.address}</span>
                            <p>{item.label}</p>
                        </div>
                    </div>
                ))}
            </div>

            {/* 底部导航栏 */}
            <div className={styles.bottom}>
                <div className={styles.second} onClick={() => navigate("/home")}>
                    <img src={hourse2} alt="" />
                    <p style={{ color: 'black' }}>首页</p>
                </div>
                <div className={styles.first} onClick={() => navigate("/game")}>
                    <img src={flower} alt="" />
                    <p>攻略</p>
                </div>
                <div className={styles.plane} onClick={aircraft}>
                    <div className={styles.aircraft}>
                        <img src={send} alt="" />
                    </div>
                    <p style={{ marginTop: '33px', textAlign: 'center' }}>发布</p>
                </div>
                <div className={styles.first} onClick={() => navigate("/ranking")}>
                    <img src={tree} alt="" />
                    <p style={{ color: '#FF5050' }}>排行榜</p>
                </div>
                <div className={styles.first} onClick={() => navigate("/mine")}>
                    <img src={mines} alt="" />
                    <p>我的</p>
                </div>
            </div>
        </div>
    );
};

export default Ranking;